package cn.tsmchina.one.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * json 工具类
 * @author  YUE
 * @date 2013-6-13 上午11:16:03
 */
public final class JsonUtil
{
	private static JsonGenerator generator = null;
	private static ObjectMapper mapper = null;
	private static ByteArrayOutputStream out =null;

	/**
	 * 把map 集合转换为 json 字符串
	 * @author  YUE
	 * @date 2013-6-13 上午11:13:35
	 * @param jsonMap
	 * @return
	 */
	public static String parseJson(Object jsonObj)
	{
		try
		{
			mapper = new ObjectMapper();
			out = new ByteArrayOutputStream();
			generator = mapper.getJsonFactory().createJsonGenerator(out, JsonEncoding.UTF8);
			generator.writeObject(jsonObj);
			return new String(out.toByteArray(),"utf-8");
		}
		catch (IOException e)
		{
			System.out.println("转换出错:"+e.getMessage());
		}
		finally
		{
			close();
		}
		return "{}";
	}
	
	/**
	 * 把map 集合转换为 jsonp 字符串
	 * @author  YUE
	 * @date 2013-6-14 上午9:55:02
	 * @param callback
	 * @param jsonObj
	 * @return
	 */
	public static String parseJsonp(String callback, Object jsonObj)
	{
		return callback+"("+parseJson(jsonObj)+")";
	}

	/**
	 * 把json 字符串转换成对象
	 * @author  YUE
	 * @date 2013-6-13 上午11:14:31
	 * @param clasz
	 * @param json
	 * @return
	 */
	public static <T> T parseObject(Class<T> clasz, String json)
	{
		try
		{
			mapper = new ObjectMapper();
			//解决反序列化报错的BUG
			mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
			return mapper.readValue(json.getBytes("utf-8"),clasz);
		}
		catch (IOException e)
		{
			System.out.println("转换出错:"+e.getMessage());
		}
		finally
		{
			close();
		}
		return null;
	}
	
	/**
	 * 关闭资源
	 * @author  YUE
	 * @date 2013-6-13 上午11:15:46
	 */
	private static void close()
	{
		if(out != null)
		{
			try
			{
				out.flush();
				out.close();
			}
			catch (IOException e)
			{
			}
			finally
			{
				out = null;
			}
		}
		if(generator != null )
		{
			try
			{
				generator.flush();
				generator.close();
			}
			catch (IOException e)
			{
			}
			finally
			{
				generator = null;
			}
		}
		mapper = null;
	}
}
